import Vue from 'vue'
import jwt from 'jsonwebtoken'
import VueRouter from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 懒加载
const Login = () => import('@/views/Login.vue')
const Userlogin = () => import('@/views/Userlogin.vue')
const School = () => import('@/views/School.vue')
const Major = () => import('@/views/Major.vue')
const Score = () => import('@/views/Score.vue')
const News = () => import('@/views/News.vue')
const Index = () => import('@/views/Index.vue')
const Control = () => import('@/views/Control.vue')
const Dashboard = () => import('@/views/Dashboard.vue')
const Admin = () => import('@/views/Admin.vue')
const User = () => import('@/views/User.vue')
const Carousel = () => import('@/views/Carousel.vue')
const SchoolList = () => import('@/views/SchoolList.vue')
const MajorList = () => import('@/views/MajorList.vue')
const NewsList = () => import('@/views/NewsList.vue')

Vue.use(VueRouter)

const router = new VueRouter({
  linkActiveClass: 'active',
  routes: [
    { path: '/', redirect: '/index' },
    { path: '/index', component: Index },
    { path: '/school', component: School },
    { path: '/major', component: Major },
    { path: '/score', component: Score },
    { path: '/news', component: News },
    { path: '/userlogin', component: Userlogin },
    { path: '/login', component: Login },
    {
      path: '/control',
      component: Control,
      children: [
        { path: '', redirect: 'dashboard' },
        { path: 'dashboard', component: Dashboard, meta: { requireAuth: true } },
        { path: 'admin', component: Admin, meta: { requireAuth: true } },
        { path: 'user', component: User, meta: { requireAuth: true } },
        { path: 'carousel', component: Carousel, meta: { requireAuth: true } },
        { path: 'schoolList', component: SchoolList, meta: { requireAuth: true } },
        { path: 'majorList', component: MajorList, meta: { requireAuth: true } },
        { path: 'newsList', component: NewsList, meta: { requireAuth: true } }
      ]
    }
  ]
})

// 验证路由登录权限
router.beforeEach((to, from, next) => {
  NProgress.start()
  const token = localStorage.getItem('Gx-Token') // 得到授权码
  let valid = token
  if (token) {
    try {
      jwt.verify(token, '0513')
    } catch (err) {
      Vue.prototype.$notify.error({ title: '授权令牌错误', message: err })
      valid = false
    }
  }

  if (valid) {
    if (to.path === '/login') next('/control')
  } else {
    if (to.meta.requireAuth) next('/login')
  }

  next()
})
// 全局后置首位，结束loading效果
router.afterEach(() => { NProgress.done() })
export default router
